package com.thesis.downloader;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import com.thesis.utils.CONSTANTS;
import com.thesis.utils.CoordinateConversion;

public class BuytTPHCMinfo {

	private final String URL_BUSMAP = "http://www.buyttphcm.com.vn/Detail_TTLT.aspx?sl=";
	private final String TAG_STARTLIST = "Thời gian chuyến";
	private final String TAG_STARTLIST3 = "Thời gian h&#224;nh tr&#236;nh:";
	private final String TAG_ENDLIST = " ph";

	private final String DEL1 = "&nbsp;";
	private final String DEL2 = "ph&#250;t";
	private final String DEL3 = " ";
	private final String DEL4 = ":";

	private final String FOLDERNAME = "bus/";

	private final String allBusRouteTime_filename = FOLDERNAME
			+ "allBusRouteTime.txt";

	// ==============================

	public BuytTPHCMinfo() {

		try {
			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(CONSTANTS.RESULT_FOLDER
							+ "bustime_summary.txt"), "UTF-8"));
			out.write("BUSROUTEno TIMEinMINUTES\n");
			for (Integer busroute : CONSTANTS.ALLBUSROUTE) {
				if (busroute < 0)
					continue;
				String url = URL_BUSMAP + String.format("%02d", busroute);
				URLConnection busRouteConnection;
				URL busRoute = new URL(url);

				busRouteConnection = busRoute.openConnection();
				BufferedReader in = new BufferedReader(new InputStreamReader(
						busRouteConnection.getInputStream()));

				String inputLine;
				String[] info;
				String[] info2;

				// out.write(url + "\n");
				out.write(busroute + " ");
				while ((inputLine = in.readLine()) != null) {
					if (inputLine.contains(TAG_STARTLIST)) {
						info = inputLine.split(TAG_STARTLIST);
						info2 = info[1].split(TAG_ENDLIST);
						String result = info2[0];
						result = result.replaceAll(DEL1, "");
						result = result.replaceAll(DEL2, "");
						result = result.replaceAll(DEL3, "");
						result = result.replaceAll(DEL4, "");
						out.write(result + "\n");
					}
					if (inputLine.contains(TAG_STARTLIST3)) {
						info = inputLine.split(TAG_STARTLIST3);
						info2 = info[1].split(TAG_ENDLIST);
						String result = info2[0];
						result = result.replaceAll(DEL1, "");
						result = result.replaceAll(DEL2, "");
						result = result.replaceAll(DEL3, "");
						result = result.replaceAll(DEL4, "");
						out.write(result + "\n");
					}
				}
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
}
